package com.ysm.smfu.fragment;

import android.app.ProgressDialog;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.app.FragmentActivity;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.text.method.DigitsKeyListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.ysm.smfu.R;
import com.ysm.smfu.activity.XiangQingActivity;
import com.ysm.smfu.activity.ZhiFuActivity;
import com.ysm.smfu.activity.ZhiFuPsdActivity;
import com.ysm.smfu.alipay.PayResult;
import com.ysm.smfu.bean.Account;
import com.ysm.smfu.bean.PayBusinessInfo;
import com.ysm.smfu.contans.SpKey;
import com.ysm.smfu.manager.GlideCircleTransform;
import com.ysm.smfu.protocal.BaseProtocal;
import com.ysm.smfu.protocal.MyStringCallBack;
import com.ysm.smfu.utils.JsonUtil;
import com.ysm.smfu.utils.PopupWindowUtil;
import com.ysm.smfu.utils.StoreInfo;
import com.ysm.smfu.utils.PrintUtil;
import com.ysm.smfu.utils.ToastUtils;
import com.ysm.smfu.utils.UIUtils;
import com.ysm.smfu.welcome.SharedConfig;
import com.tencent.mm.sdk.modelpay.PayReq;
import com.tencent.mm.sdk.openapi.IWXAPI;
import com.tencent.mm.sdk.openapi.WXAPIFactory;
import com.zhy.autolayout.AutoLinearLayout;
import com.zhy.autolayout.AutoRelativeLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by Administrator on 2016/10/12.
 */
public class YuErFragment extends MyBaseFragment implements View.OnClickListener {

    private static final String YE = "yuer";
    private static final int SDK_PAY_FLAG = 100;
    private static final int SDK_PAY_FLAG_NOCODE = 101;

    @BindView(R.id.aaa)
    AutoLinearLayout aaa;
    //    输入付款金额
    @BindView(R.id.fragment_shoukuan_num)
    EditText fragmentShoukuanNum;
    //    点击打开付款方式
    @BindView(R.id.fragment_shoukuan_pay)
    TextView fragmentShoukuanPay;

    //    将付款金额
    @BindView(R.id.will_pay_money)
    TextView will_pay_money;

    @BindView(R.id.yuerfragment)
    AutoRelativeLayout yuerfragment;
    @BindView(R.id.fragment_shoukuan_img)
    ImageView fragmentShoukuanImg;
    @BindView(R.id.fragment_shoukuan_text)
    TextView fragmentShoukuanText;
    //    账单详情
    @BindView(R.id.fragment_shoukuan_zhangdan_detail)
    TextView fragment_shoukuan_zhangdan_detail;

    private String userId = "";

    private String name;
    private Account account;
    private SharedPreferences currShared;
    private String level;
    private String aliPayUrl;
    private PayBusinessInfo payBusinessInfo;
    private String payResponse;
    private IWXAPI api;
    private String[] prePayInfos;
    private ProgressDialog dialog;

    private String pay_businessid = "";
    private String jifen = "";
    private String money = "";
    private String remark = "";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = UIUtils.inflate(R.layout.fragment_shoukuan);
        ButterKnife.bind(this, view);
        //        账单详情
        fragment_shoukuan_zhangdan_detail.setOnClickListener(this);
        getData();
        //        输入小数点
        fragmentShoukuanNum.setKeyListener(new DigitsKeyListener(false, true));
        return view;
    }

    /**
     * 获取需要数据
     */
    private void getData() {
        name = new SharedConfig(UIUtils.getContext()).getCommoneSp().getString(SpKey.NAME, "");
        currShared = new SharedConfig(UIUtils.getContext(), name).getPrivateSp();
        userId = currShared.getString(SpKey.USERID, "");
        level = currShared.getString(SpKey.LEVEL, "");
        Bundle arguments = getArguments();
        if (arguments != null) {
            pay_businessid = arguments.getString(SpKey.Pay_BUSSINESSID);
            money = arguments.getString(SpKey.MONEY);
            jifen = arguments.getString(SpKey.JIFEN);
            remark = arguments.getString(SpKey.REMARK);
            storePayInfo();
        }
        getShanghuInfoByBusinessId(pay_businessid);
    }

    /**
     * 保存支付信息
     */
    public void storePayInfo() {
        //保存到本地，以便在用户支付一半，重新选择支付时提取支付信息
        currShared.edit().putString(SpKey.Pay_BUSSINESSID, pay_businessid).commit();
        currShared.edit().putString(SpKey.PAY_PRICE, money).commit();
        currShared.edit().putString(SpKey.JIFEN, jifen).commit();
        currShared.edit().putString(SpKey.REMARK, remark).commit();
    }

    /**
     * 通过businessId获取商户信息
     * /business/toPrePayPage
     * businessId:商家ID
     */
    private void getShanghuInfoByBusinessId(String businessId) {
        BaseProtocal.builder(true).getShanghuInfoByBusinessId(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("商户信息", response);
                String state = JsonUtil.getState(response);
                if (!TextUtils.equals(state, "1")) {
                    ToastUtils.showToast(JsonUtil.getMessage(response));
                    return;
                }
                payBusinessInfo = new Gson().fromJson(response, PayBusinessInfo.class);
                setBasicPage();
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.showErrToast();
            }
        }, businessId);
    }

    /**
     * 设置基本页面
     */
    private void setBasicPage() {
        if (TextUtils.isEmpty(money) && TextUtils.isEmpty(jifen)) {
            will_pay_money.setVisibility(View.INVISIBLE);
            fragment_shoukuan_zhangdan_detail.setVisibility(View.INVISIBLE);
            aaa.setVisibility(View.VISIBLE);
        } else {
            will_pay_money.setVisibility(View.VISIBLE);
            fragment_shoukuan_zhangdan_detail.setVisibility(View.VISIBLE);
            aaa.setVisibility(View.INVISIBLE);
            if (!money.contains("."))
                money = money + ".00";
            else {
                String[] split = money.split("\\.");
                if (split != null && split[1].length() == 1)
                    money = money + "0";
            }
            String data = "";

            if (!TextUtils.isEmpty(money) && !TextUtils.equals(money, "0.00"))
                data = "-￥" + money;
            if (!TextUtils.isEmpty(jifen) && !TextUtils.equals(jifen, "0"))
                if (TextUtils.isEmpty(data))
                    data = "-" + jifen + "兑换券";
                else
                    data = data + "      -" + jifen + "兑换券";
            will_pay_money.setText(data);
        }
        if (payBusinessInfo.bi != null && !TextUtils.isEmpty(payBusinessInfo.bi.headPhoto) && !payBusinessInfo.bi.headPhoto.startsWith("null?"))
            Glide.with(YuErFragment.this).load(payBusinessInfo.bi.headPhoto).placeholder(R.drawable.myimg2).error(R.drawable.myimg2)
                    .override(200, 200)
                    .centerCrop()
                    .transform(new GlideCircleTransform(UIUtils.getContext()))
                    .into(fragmentShoukuanImg);
        if (payBusinessInfo.bi != null)
            fragmentShoukuanText.setText(payBusinessInfo.bi.name);
    }


    @OnClick({R.id.fragment_shoukuan_pay})
    public void onclick(View view) {
        switch (view.getId()) {
            case R.id.fragment_shoukuan_pay:
//                没有登录则跳往登录页
                if (BaseProtocal.isGoLogin(true, getActivity()))
                    return;
                getPayInfo();
                //如果是空白二维码扫描过来
                if (TextUtils.isEmpty(money) && TextUtils.isEmpty(jifen)) {
                    money = fragmentShoukuanNum.getText().toString().trim();
//                    金额不能小于0.1元
                    if (TextUtils.isEmpty(money) || Double.parseDouble(money) < 0.01) {
                        ToastUtils.showToast("金额须大于0.01元");
                        break;
                    }
                    currShared.edit().putString(SpKey.PAY_PRICE, money).commit();
                } else if ((TextUtils.equals(money, "0.00")
                        || TextUtils.equals(money, "0") || TextUtils.equals(money, "0.0") || TextUtils.isEmpty(money))
                        && !(TextUtils.equals(jifen, "0") || TextUtils.isEmpty(jifen))) {
//                    如果金额为0,兑换券不为0，直接跳转到余额支付
                    chechZhiFuPsdState();
                    PopupWindowUtil.cancel(YE, null);
                    break;
                }
                View pw_yuer = PopupWindowUtil.toogleInButton(getActivity(), YE, this.yuerfragment, R.layout.fragment_shoukuan_pw, null);
                setPopupListener(pw_yuer);
                UIUtils.hideKeyboard(this);
                break;
        }
    }

    /**
     * 获取支付参数
     */
    private void getPayInfo() {
        money = currShared.getString(SpKey.PAY_PRICE, "");
        jifen = currShared.getString(SpKey.JIFEN, "");
        remark = currShared.getString(SpKey.REMARK, "");
        pay_businessid = currShared.getString(SpKey.Pay_BUSSINESSID, "");
    }

    public void setPopupListener(View view) {
        AutoLinearLayout fragment_pw_yuer = (AutoLinearLayout) view.findViewById(R.id.fragment_pw_yuer);
        TextView fragment_pw_yuer_text = (TextView) view.findViewById(R.id.fragment_pw_yuer_text);
        getYuer(fragment_pw_yuer_text);
        AutoLinearLayout fragment_pw_alipay = (AutoLinearLayout) view.findViewById(R.id.fragment_pw_alipay);
//        AutoLinearLayout fragment_pw_wx = (AutoLinearLayout) view.findViewById(R.id.fragment_pw_wx);//微信支付
        TextView cancel = (TextView) view.findViewById(R.id.cancel);
        fragment_pw_yuer.setOnClickListener(this);
        fragment_pw_alipay.setOnClickListener(this);
//        fragment_pw_wx.setOnClickListener(this);
        cancel.setOnClickListener(this);
    }

    /**
     * 获取余额
     *
     * @param fragment_pw_yuer_text
     */
    private void getYuer(final TextView fragment_pw_yuer_text) {
        BaseProtocal.builder(true).getYuEr(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                String state = JsonUtil.getState(response);
                if (TextUtils.equals(state, "1")) {
                    try {
                        JSONObject jsonObject = new JSONObject(response);
                        String acc = jsonObject.optString("account");
                        account = new Gson().fromJson(acc, Account.class);
//                        设置积分余额
                        String s = String.valueOf(account.balance).split("\\.")[1];
                        if (s != null && s.length() == 1)
                            fragment_pw_yuer_text.setText("￥" + account.balance + "0");
                        else
                            fragment_pw_yuer_text.setText("￥" + account.balance);
                    } catch (JSONException e) {

                    }
                } else {
                    ToastUtils.showErrToast();
                }
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.showErrToast();
            }
        });
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.fragment_pw_yuer:
                //  判断是否设置过支付密码
                chechZhiFuPsdState();
                PopupWindowUtil.cancel(YE, null);
                break;
            case R.id.fragment_pw_alipay:
//                支付宝支付
                aliPayNoCode(pay_businessid);
                PopupWindowUtil.cancel(YE, null);
                break;
//            case R.id.fragment_pw_wx:
//                ToastUtils.showToast(getContext(),"该功能尚未开通");
////                微信支付
////                wxPrePay(pay_businessid);
////                PopupWindowUtil.cancel(YE, null);
//                break;
            case R.id.cancel:
//                取消
                PopupWindowUtil.cancel(YE, null);
                break;
            case R.id.fragment_shoukuan_zhangdan_detail:
                createPayInfo();
//                账单详情,传递过去数据
                Intent intent2 = new Intent(getActivity(), XiangQingActivity.class);
                intent2.putExtra(SpKey.PAYBUSINESSINFO, payBusinessInfo);
                intent2.putExtra("xiangqing", 0);
                startActivity(intent2);
                PopupWindowUtil.cancel(YE, null);
                break;
        }
    }

    /**
     * 为payBusinessInfo赋值
     */
    private void createPayInfo() {
        if (TextUtils.isEmpty(money))
            money = "0";
        if (TextUtils.isEmpty(jifen))
            jifen = "0";
        payBusinessInfo.price = money;
        payBusinessInfo.pointsNum = jifen;
        payBusinessInfo.remark = remark;
    }

    /**
     * 正在加载
     */
    private void showDialog() {
        dialog = ProgressDialog.show(getActivity(), "", "正在加载...", true, false);
        if (dialog.isShowing())
            dialog.dismiss();
        dialog.show();
    }

    public void cancelDialog() {
        if (dialog != null && dialog.isShowing()) {
            dialog.dismiss();
        }
    }

    String returnPoints;

    /**
     * 微信支付
     * lineManualWeChatPay
     *
     * @param businessid
     */
    public void wxPrePay(String businessid) {
        if (prePayInfos == null)
            BaseProtocal.builder(true).wxPrePay(new MyStringCallBack() {
                @Override
                public void onSuccess(String response) {
                    PrintUtil.printRespones("微信支付信息", prePayInfos.toString());
                    String state = JsonUtil.getState(response);
                    if (TextUtils.equals(state, "1")) {
                        prePayInfos = JsonUtil.getPrePayInfo(response);
                        returnPoints = prePayInfos[1];
                        wChatPay(prePayInfos[0]);
                    } else
                        ToastUtils.showToast(JsonUtil.getMessage(response));
                }

                @Override
                public void onFail(Exception e) {
                }
            }, businessid, money, jifen);
        else {
            returnPoints = prePayInfos[1];
            wChatPay(prePayInfos[0]);
        }
    }

    /**
     * 微信支付
     */
    private void wChatPay(String response) {
        // 将该app注册到微信
        if (api == null) {
            api = WXAPIFactory.createWXAPI(UIUtils.getContext(), SpKey.WXAPPID, false);
            api.registerApp(SpKey.WXAPPID);
        }
        try {
            JSONObject json = new JSONObject(response);
            PayReq req = new PayReq();
            req.appId = json.getString("appid");
            req.partnerId = json.getString("partnerid");
            req.prepayId = json.getString("prepayid");
            req.nonceStr = json.getString("noncestr");
            req.timeStamp = json.getString("timestamp");
            req.packageValue = json.getString("package");
            req.sign = json.getString("sign");
//            req.extData = "app data";
            saveForShowSuccessInf();
            api.sendReq(req);
        } catch (JSONException e) {

        }
    }

    /**
     * 发送广播用于展示成功信息
     */
    private void saveForShowSuccessInf() {
        if (payBusinessInfo != null) {
            if (payBusinessInfo.payInfo != null) {
                currShared.edit().putString("payInfo_price", payBusinessInfo.payInfo.price).commit();
                currShared.edit().putString("payInfo_points", payBusinessInfo.payInfo.pointsNum).commit();
            } else
                currShared.edit().putString("payInfo_price", money).commit();
            currShared.edit().putString("payInfo_name", payBusinessInfo.bi.name).commit();
            currShared.edit().putString("payInfo_headPhoto", payBusinessInfo.bi.headPhoto).commit();
        }
        currShared.edit().putString("payInfo_returnPoints", returnPoints).commit();
    }

    /**
     * 提示对话框--没有点击事件
     *
     * @param activity
     * @param msg
     */
    public void showErrorDialog(FragmentActivity activity, String msg) {
        AlertDialog dialog = new AlertDialog.Builder(activity).setMessage(msg)
                .setNegativeButton("确定", null).create();
        dialog.show();
    }

    /**
     * 调用支付宝
     * /lineManualBalancePay
     *
     * @param businessId
     */
    private void aliPayNoCode(String businessId) {
        BaseProtocal.builder(true).aliPayNoCode(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
                PrintUtil.printRespones("支付宝返回信息", response);
                payResponse = response;
                String state = JsonUtil.getState(response);
                if (!TextUtils.equals(state, "1")) {
                    ToastUtils.showToast(JsonUtil.getMessage(response));
                    return;
                }

                aliPayUrl = JsonUtil.getAliPayUrl(response);
                if (!TextUtils.isEmpty(aliPayUrl)) {// 订单信息
                    Runnable payRunnable = new Runnable() {
                        @Override
                        public void run() {
                            PayTask alipay = new PayTask(getActivity());
                            Map<String, String> result = alipay.payV2(aliPayUrl, true);
                            Message msg = new Message();
                            msg.what = SDK_PAY_FLAG_NOCODE;
                            msg.obj = result;
                            mHandler.sendMessage(msg);
                        }
                    };
                    // 必须异步调用
                    Thread payThread = new Thread(payRunnable);
                    payThread.start();
                }
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.showErrToast();
            }
        }, businessId, money, jifen);
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            @SuppressWarnings("unchecked")
            PayResult payResult = new PayResult((Map<String, String>) msg.obj);
            /**
             对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
             */
            String resultStatus = payResult.getResultStatus();
            // 判断resultStatus 为9000则代表支付成功
            if (TextUtils.equals(resultStatus, "9000")) {
                // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                Toast.makeText(getActivity(), "支付成功", Toast.LENGTH_SHORT).show();
                if (!TextUtils.isEmpty(aliPayUrl) && payBusinessInfo != null) {
                    try {
                        JSONObject jsonObject = new JSONObject(payResponse);
                        String resParams = jsonObject.optString("resParams");
                        com.ysm.smfu.bean.PayResult payResult1 = new Gson().fromJson(resParams, com.ysm.smfu.bean.PayResult.class);
                        payResult1.price = money;
                        payResult1.name = payBusinessInfo.bi.name;
                        payResult1.headPhone = payBusinessInfo.bi.headPhoto;
//                                支付成功后，跳转支付成功界面
                        Intent intent = new Intent(getActivity(), XiangQingActivity.class);
                        intent.putExtra("xiangqing", 1);
                        intent.putExtra(SpKey.PAYRESULT, payResult1);
                        startActivity(intent);
                        StoreInfo.getInstance().clearPayInfo(currShared);
                    } catch (JSONException e) {

                    }
                }
            } else {
                // 该笔订单真实的支付结果，需要依赖服务端的异步通知。
                Toast.makeText(getActivity(), "支付失败", Toast.LENGTH_SHORT).show();
            }
        }
    };

    /**
     * 检测支付密码设置状态
     */
    private void chechZhiFuPsdState() {

        BaseProtocal.builder(true).checkZhiFuPsdState(new MyStringCallBack() {
            @Override
            public void onSuccess(String response) {
//                cancelDialog();
                try {
                    JSONObject jsonObject = new JSONObject(response);
                    String state = jsonObject.optString("state");
                    if (TextUtils.equals(state, "1")) {
//                    余额支付
                        payMoneyAndJiFen();
                    } else if (TextUtils.equals(state, "0")) {
                        //设置支付密码
                        Intent intent = new Intent(getActivity(), ZhiFuPsdActivity.class);
                        startActivityForResult(intent, 200);
                    }
                } catch (JSONException e) {

                }
            }

            @Override
            public void onFail(Exception e) {
                ToastUtils.showErrToast();
            }
        }, userId);
    }

    /**
     * 支付金钱和积分
     */
    private void payMoneyAndJiFen() {
        Intent intent = new Intent(getActivity(), ZhiFuActivity.class);
        intent.putExtra(SpKey.Pay_BUSSINESSID, pay_businessid);
        intent.putExtra(SpKey.MONEY, money);
        intent.putExtra(SpKey.JIFEN, jifen);
        startActivity(intent);
    }

    @Override
    public void onStop() {
        super.onStop();
//        pay_businessid = "";
//        jifen = "";
//        money = "";
//        remark = "";
        cancelDialog();
        PopupWindowUtil.cancel(YE, null);
    }
}
